package com.inspection.utils;

import com.inspection.model.HostInfo;

import java.io.*;
import java.net.*;
import java.util.concurrent.*;
import java.util.logging.Logger;

/**
 * Created by zhujun on 2015-6-5.
 */
public class ClientWait {

    Logger logger = Logger.getLogger(ClientWait.class.getName());

    private int port=8821;
    private ServerSocket serverSocket;
    private ExecutorService executorService;//线程池
    private final int POOL_SIZE=10;//单个CPU线程池大小

    public ClientWait() throws IOException{
        serverSocket=new ServerSocket(port);
        //Runtime的availableProcessor()方法返回当前系统的CPU数目.
        executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
        logger.info("Node Server is start !");
    }

    public void service(){
        while(true){
            Socket socket=null;
            try {
                //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
                socket=serverSocket.accept();
                executorService.execute(new Handler(socket));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



}

class Handler implements Runnable{

    Logger logger = Logger.getLogger(Handler.class.getName());

    private Socket socket;
    public Handler(Socket socket){
        this.socket=socket;
    }
    private PrintStream getWriter(Socket socket) throws IOException{
        OutputStream socketOut=socket.getOutputStream();
        return new PrintStream(socketOut,true);
    }
    private BufferedReader getReader(Socket socket) throws IOException{
        InputStream socketIn=socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn));
    }
    public String echo(String msg){
        return "echo:"+msg;
    }
    public void run(){
        try {
            logger.info("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());

            HostInfo hostInfo = new HostUtil().getInfo();

            OutputStream socketOut=socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(socketOut);
            oos.writeObject(hostInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
